using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Adopted;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;
using System.Transactions;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Adopted
{
    /// <summary>
    /// 领用申请添加处理程序
    /// </summary>
    public class AddAdoptedCommandHnadler : IRequestHandler<AddAdoptedCommands, ApiResult<int>>
    {
        private readonly ILogger<AddAdoptedCommandHnadler> logger;
        private readonly IBaseRepository<TouseTable> touseRep;
        private readonly IBaseRepository<ItemTable> itemRep;
        private readonly MedicalDbContext dbContext;

        /// <summary>
        /// 构造函数，注入所需依赖
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="touseRep">领用表仓储</param>
        /// <param name="itemRep">物品表仓储</param>
        /// <param name="dbContext">数据库上下文</param>
        public AddAdoptedCommandHnadler(
            ILogger<AddAdoptedCommandHnadler> logger, 
            IBaseRepository<TouseTable> touseRep, 
            IBaseRepository<ItemTable> itemRep,
            MedicalDbContext dbContext)
        {
            this.logger = logger;
            this.touseRep = touseRep;
            this.itemRep = itemRep;
            this.dbContext = dbContext;
        }

        /// <summary>
        /// 处理领用申请添加命令
        /// </summary>
        /// <param name="request">领用申请命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API结果</returns>
        public async Task<ApiResult<int>> Handle(AddAdoptedCommands request, CancellationToken cancellationToken)
        {
            // 开启数据库事务
            using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
            try
            {
                // 验证领用申请数据
                if (request.touseTable == null)
                {
                    logger.LogWarning("领用申请数据为空");
                    return new ApiResult<int>()
                    {
                         Code = ApiEnums.Fail,
                         Data = 1,
                         Msg = "领用申请数据不能为空"
                    }; 
                }
                
                // 设置默认值
                if (request.touseTable.ApplicationTime == default)
                {
                    request.touseTable.ApplicationTime = DateTime.Now;
                }
                
                // 设置删除标志为未删除
                request.touseTable.IsDeleted = false;

                // 添加领用申请
                touseRep.Create(request.touseTable);
                await dbContext.SaveChangesAsync(cancellationToken);
                
                
                
                // 提交事务
                await transaction.CommitAsync(cancellationToken);
                
                logger.LogInformation("成功添加领用申请，ID：{Id}", request.touseTable.Id);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Data = request.touseTable.Id,
                    Msg = "成功添加领用申请"
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                await transaction.RollbackAsync(cancellationToken);
                
                logger.LogError(ex, "添加领用申请时发生错误：{Message}", ex.Message);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Data = 1,
                    Msg = "添加领用申请失败"
                };
            }
        }
    }
}